package com.ljq.mantou;

/**
 * 饺子馆
 * 
 * @author linjq 饺子：JiaoZi 盘子：PanZi，有最大装载数量(只有一个) 客人： Eatter，盘子有饺子就吃 制作师父：
 *         Makker， 盘子小于最大值，继续制作
 *
 */
public class DummplingStore {

	public static void main(String[] args) {
		PanZi panZi = new PanZi(5);
		Thread a1 = new Thread(new Makker(panZi), "制作师父");
		Thread a2 = new Thread(new Eatter(panZi), "客人");
		Thread a3 = new Thread(new Eatter(panZi), "客人2");
		a1.start();
		a2.start();
		// a3.start();
	}
}

class JiaoZi {
	int id;

	@Override
	public String toString() {
		return "饺子 [" + id + "]";
	}

}

/**
 * 盘子装饺子
 * 
 * @author linjq
 *
 */
class PanZi {

	private int max; // 默认最大值
	private JiaoZi[] jiaoArr; // 饺子数组，我要明确的知道这是第几个饺子
	private int num = 0; // 盘子中的数量

	public PanZi(int max) {
		super();
		this.max = max;
		this.jiaoArr = new JiaoZi[this.max];
	}

	// 做好饺子放进盘子
	public synchronized void put(JiaoZi jiaoZi) {
		// 如果最大，就先休息不做了
		while (num == jiaoArr.length) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		jiaoArr[num] = jiaoZi;
		System.out.println(Thread.currentThread().getName() + "制作第【" + jiaoArr[num] + "】");
		num++;
	}

	// 吃饺子从盘子取
	public synchronized JiaoZi get() {
		// 如果还剩一个，就休息不吃了
		while (num == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();

		num--;
		System.out.println(Thread.currentThread().getName() + "吃掉第【" + jiaoArr[num] + "】个饺子");
		return jiaoArr[num];
	}
}

/**
 * 吃饺子的人
 * 
 * @author linjq
 *
 */
class Eatter implements Runnable {

	private PanZi panzi;

	public Eatter(PanZi panZi) {
		this.panzi = panZi;
	}

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			JiaoZi jiaoZi = panzi.get();
			try {
				Thread.sleep((int) (Math.random() * 1000)); // 客人边吃边聊，休息一下
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName() + "吃饱了回家");
	}

}

/**
 * 做饺子
 * 
 * @author linjq
 *
 */
class Makker implements Runnable {
	private PanZi panzi;

	public Makker(PanZi panZi) {
		this.panzi = panZi;
	}

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			JiaoZi jiaoZi = new JiaoZi();
			jiaoZi.id = i;
			this.panzi.put(jiaoZi);

			try {
				Thread.sleep((int) (Math.random() * 200)); // 师父竟竟业业包饺子赚钱
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName() + "饺子全部做完，收工");

	}
}